package com.songshuai.webapi.permission.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.DateUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.permission.common.enumerations.DepartmentLevelTypeEnum;
import com.songshuai.webapi.permission.common.enumerations.error.DepartmentError;
import com.songshuai.webapi.permission.dao.*;
import com.songshuai.webapi.permission.dto.po.CampusIdCheckPojo;
import com.songshuai.webapi.permission.dto.po.RoleUserListReqPojo;
import com.songshuai.webapi.permission.dto.po.RolesReqPojo;
import com.songshuai.webapi.permission.dto.po.UserIdsForRolePojo;
import com.songshuai.webapi.permission.dto.request.*;
import com.songshuai.webapi.permission.dto.response.*;
import com.songshuai.webapi.permission.model.*;
import com.songshuai.webapi.permission.service.CampusService;
import com.songshuai.webapi.permission.service.CurrentUserService;
import com.songshuai.webapi.permission.service.NavigationsService;
import com.songshuai.webapi.permission.service.RolesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.*;

@Slf4j
@Service
public class RolesServiceImpl implements RolesService {

    @Autowired
    private YxRolesMapper rolesMapper;

    @Autowired
    private YxUserRolesMapper userRolesMapper;

    @Autowired
    private  YxRoleNavigationFunctionMapper roleNavigationFunctionMapper;

    @Autowired
    private YxRolesNavigationsMapper rolesNavigationsMapper;

    @Autowired
    private YxNavigationsMapper navigationsMapper;

    @Autowired
    private YxHomepageConfigMapper homepageConfigMapper;

    @Autowired
    private NavigationsService navigationsService;

    @Autowired
    private CurrentUserService currentUserService;

    @Autowired
    private YxDepartmentsMapper yxDepartmentsMapper;


    @Autowired
    private YxDepartmentUserMapper yxDepartmentUserMapper;

    @Autowired
    private YxDepartmentRelationMapper departmentRelationMapper;

    @Autowired
    private YxDepartmentLeaderMapper departmentLeaderMapper;

    @Autowired
    private CampusService campusService;

    /**
     * 查询角色列表
     * @param parmDto
     * @return
     */
    @Override
    public  QueryResponse<List<RoleListResDto>> queryRolesList(BaseParmDto<RolesReqDto> parmDto) {
        Integer campusCode= DepartmentLevelTypeEnum.Campus.getCode();
        RolesReqDto reqDto=parmDto.getParam();
        RolesReqPojo rolesReqPojo=new RolesReqPojo();
        PropertiesUtil.copyProperties(reqDto,rolesReqPojo);

        //校区模糊搜索 适配校区名字等于“乂学教育”、“乂”、“学”、“教”、“育”、“乂学”、“教育”等
        String campusName=rolesReqPojo.getCampusName();
        Integer zeroInteger=new Integer(0);
       if((!StringUtils.isEmpty(campusName))&&"乂学教育".indexOf(campusName)!=-1){
            rolesReqPojo.setCampusDimName(rolesReqPojo.getCampusName());
            rolesReqPojo.setCampusName("");
            rolesReqPojo.setCampusId(null);
            rolesReqPojo.setCampusCode(campusCode);
        }

        //当前登录用户ID
        Integer loginUserId=currentUserService.getUserId();
        String campusIdStr=reqDto.getCampusId();
        if(StringUtils.isEmpty(campusIdStr)){
            rolesReqPojo.setCampusId(null);
            rolesReqPojo.setCampusCodeFlag(null);
        }else if("0".equals(campusIdStr)){
            rolesReqPojo.setCampusCodeFlag(new Integer(0));
            rolesReqPojo.setCampusId(null);
        }else{
            rolesReqPojo.setCampusId(Integer.parseInt(campusIdStr));
            rolesReqPojo.setCampusCodeFlag(null);
        }

        rolesReqPojo.setUserId(loginUserId);
        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        log.info("当前登录人是否是超级管理员："+isSysAdmin+"，人员ID是"+loginUserId);
        rolesReqPojo.setSysAdmin(isSysAdmin);
        /*Set<Integer> leaderIdList =new HashSet<Integer>();
        //判断登录用户是部门领导，还是普通用户
        if(departmentLeaderMapper.countByUserId(loginUserId)>0){
            log.info("当前登录人是部门领导，人员ID是"+loginUserId);
           //大于0，说明是部门领导
            Set<Integer> deptIdList=departmentRelationMapper.selectChildDeptIdList(loginUserId);
            if(CollectionUtils.isNotEmpty(deptIdList)){
                leaderIdList =departmentLeaderMapper.queryUserIdListByDeptIds(deptIdList);
            }
            rolesReqPojo.setUserIdList(leaderIdList);
       }*/
        Page<Object> page = PageHelper.startPage(parmDto.getPageIndex(), parmDto.getPageSize());
        List<RoleListResDto> resDtosList = rolesMapper.queryRoleListByPage(rolesReqPojo);
        //校区级别，campusLevelType==6001001，展示校区名字。campusLevelType!=6001001，将campusName重置为"无"
       Integer oneObj=new Integer(1);
        for (RoleListResDto roleListResDto:resDtosList){
            Integer campusLevelType=roleListResDto.getCampusLevelType();
            if((!isSysAdmin)&&(oneObj.equals(roleListResDto.getIsBuiltin()))) {
                //非超级管理员时，系统角色不能维护（修改和删除）。
                roleListResDto.setPrivilege(false);
            }
            if(!campusCode.equals(campusLevelType)) {
                //非校区的角色，campusName显示"无"
               roleListResDto.setCampusName("无");
            }
        }
        return QueryPageRes.setQueryResponseData(resDtosList, page.getTotal());
    }

    /**
     * 新增角色
     * @param roleAddDto
     * @return
     */
    @Transactional
    public QueryResponse insert(RoleAddDto roleAddDto) {
        YxRoles yxRole = new YxRoles();
        Date date = new Date();
        PropertiesUtil.copyProperties(roleAddDto,yxRole);
        String campusIdStr=roleAddDto.getCampusId();
        if(StringUtils.isEmpty(campusIdStr)||"0".equals(campusIdStr)){
            roleAddDto.setCampusId(null);
        }else{
            yxRole.setCampusId(Integer.parseInt(campusIdStr));
        }
        if(rolesMapper.checkRoleName(yxRole)>0){
            return new QueryResponse(ResultStatus.ROLE_NAME_REPEAT);
        }

        Integer currentLoginId=currentUserService.getUserId();
        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        log.info("当前登录人是否是超级管理员："+isSysAdmin+"，人员ID是"+currentLoginId);
        //校验校区ID
        Integer campusId=yxRole.getCampusId();
        if(!StringUtils.isEmpty(campusId)){
            //校区ID校验Pojo
            CampusIdCheckPojo campusIdCheckPojo=new CampusIdCheckPojo();
            campusIdCheckPojo.setCampusId(campusId);
            campusIdCheckPojo.setSysAdmin(isSysAdmin);
            campusIdCheckPojo.setUserId(currentLoginId);
            campusIdCheckPojo.setCampusLevelType(DepartmentLevelTypeEnum.Campus.getCode());
           if(!campusService.checkCampusId(campusId)){
                return new QueryResponse(ResultStatus.CAMPUS_ID_NO_EXIST);
            }
        }
        //校验开始时间
        String startTimeStr=roleAddDto.getStartTime();
        if(!StringUtils.isEmpty(startTimeStr)){
           if(DateUtil.isDateStr(startTimeStr)){
               yxRole.setStartTime(DateUtil.ChangeStringToDate(startTimeStr,DateUtil.dateFormat));
           }else{
               return new QueryResponse(ResultStatus.DATE_FORMAT_ERROR);
           }
        }
        //校验结束时间
        String endTimeStr=roleAddDto.getEndTime();
        if(!StringUtils.isEmpty(endTimeStr)){
            if(DateUtil.isDateStr(endTimeStr)){
                yxRole.setEndTime(DateUtil.ChangeStringToDate(endTimeStr,DateUtil.dateFormat));
            }else{
                return new QueryResponse(ResultStatus.DATE_FORMAT_ERROR);
            }
        }
        yxRole.setCreateTime(date);
        //parentId暂时先都设置为0
        yxRole.setParentId(0);
        //创建人为当前登录用户
        yxRole.setCreateId(currentLoginId);
        if(null==yxRole.getStartTime()){
            yxRole.setStartTime(date);
        }
        if(null==yxRole.getEndTime()){
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR,99);//增加10年
            yxRole.setEndTime(cal.getTime());
        }
        if(yxRole.getEndTime().compareTo(yxRole.getStartTime())<0){
            //角色开始时间不能大于结束时间
            return new QueryResponse(ResultStatus.ROLE_START_TIME_ERROR);
        }
        int  roleNum = rolesMapper.insert(yxRole);
        //int  roleId= yxRole.getRoleId();
        //插入用户角色中间表信息，让角色创建人可以查询到新建角色
        /*YxUserRoles userRole=new YxUserRoles();
        userRole.setUserId(currentUserService.getUserId());
        userRole.setRoleId(roleId);
        //当前登录人
        userRole.setCreateBy(currentUserService.getUserId());
        int userRoleNum=userRolesMapper.insert(userRole);*/
        //if(roleNum>0&&userRoleNum>0){
        if(roleNum>0){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_CREATE_FAILED);
    }

    /**
     * 更新角色
     * @param roleEditDto
     * @return
     */
    public QueryResponse updateByRoleId(RoleEditDto roleEditDto ) {
        if(!checkPrivilege(roleEditDto.getRoleId())) {
           //用户无权限操作
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        YxRoles yxRole = new YxRoles();
        PropertiesUtil.copyProperties(roleEditDto,yxRole);
        String campusIdStr=roleEditDto.getCampusId();
        if(StringUtils.isEmpty(campusIdStr)){
            roleEditDto.setCampusId(null);
        }else{
            yxRole.setCampusId(Integer.parseInt(campusIdStr));
        }
        if(rolesMapper.checkRoleName(yxRole)>0){
            return new QueryResponse(ResultStatus.ROLE_NAME_REPEAT);
        }
        //校验开始时间
        String startTimeStr=roleEditDto.getStartTime();
        if(!StringUtils.isEmpty(startTimeStr)){
            if(DateUtil.isDateStr(startTimeStr)){
                yxRole.setStartTime(DateUtil.ChangeStringToDate(startTimeStr,DateUtil.dateFormat));
            }else{
                return new QueryResponse(ResultStatus.DATE_FORMAT_ERROR);
            }
        }
        //校验结束时间
        String endTimeStr=roleEditDto.getEndTime();
        if(!StringUtils.isEmpty(endTimeStr)){
            if(DateUtil.isDateStr(endTimeStr)){
                yxRole.setEndTime(DateUtil.ChangeStringToDate(endTimeStr,DateUtil.dateFormat));
            }else{
                return new QueryResponse(ResultStatus.DATE_FORMAT_ERROR);
            }
        }
        Date date = new Date();
        if(null==yxRole.getStartTime()){
            yxRole.setStartTime(date);
        }
        if(null==yxRole.getEndTime()){
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);//设置起时间
            cal.add(Calendar.YEAR,99);//增加10年
            yxRole.setEndTime(cal.getTime());
        }
        if(yxRole.getEndTime().compareTo(yxRole.getStartTime())<0){
            //角色开始时间不能大于结束时间
            return new QueryResponse(ResultStatus.ROLE_START_TIME_ERROR);
        }
        yxRole.setUpdateTime(date);
        yxRole.setUpdateId(currentUserService.getUserId());
        int updateNum=rolesMapper.updateSelective(yxRole);
        if(updateNum>0){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @Transactional
    public QueryResponse deleteRoleById(Integer roleId) {
        if(!checkPrivilege(roleId)){
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        //删除时，校验用户是否存在用户
        int countUser=userRolesMapper.countRoleUser(roleId);
        if(countUser>0){
            return new QueryResponse(ResultStatus.ROLE_USER_EXIST_ERROR);
        }

        //然后，将中间表相应信息物理删除
        userRolesMapper.deleteByRoleId(roleId);
        roleNavigationFunctionMapper.deleteByRoleId(roleId);
        rolesNavigationsMapper.deleteByRoleId(roleId);

        //根据ID逻辑删除角色表
        YxRoles role=new YxRoles();
        role.setRoleId(roleId);
        role.setIsDelete("1");
        role.setUpdateTime(new Date());
        role.setUpdateId(currentUserService.getUserId());
        int result=rolesMapper.updateSelective(role);
        if(result>0){
            return new QueryResponse();
        }else{
            return new QueryResponse(ResultStatus.ERROR_DELETE_FAILED);
        }
    }

    /**
     * 启用、禁用角色
     * @param roleEnabledDto
     * @return
     */
    public QueryResponse enabledRoleById(RoleEnabledDto roleEnabledDto ) {
        if(!checkPrivilege(roleEnabledDto.getRoleId())) {
            //用户无权限操作
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        if(0!=roleEnabledDto.getEnabled()&&1!=roleEnabledDto.getEnabled()){
            return new QueryResponse(ResultStatus.ERROR_INVALID_ARGUMENT);
        }
        YxRoles yxRole = new YxRoles();
        PropertiesUtil.copyProperties(roleEnabledDto,yxRole);
        Date date = new Date();
        yxRole.setUpdateTime(date);
        yxRole.setUpdateId(currentUserService.getUserId());
        int updateNum=rolesMapper.updateSelective(yxRole);
        if(updateNum>0){
            return new QueryResponse();
        }
        return new QueryResponse(ResultStatus.ERROR_UPDATE_FAILED);
    }

    /**
     * 根据角色ID和APPID,查询菜单列表，并标注首页打勾项
     * @param reqDto 角色首页请求实体
     * @return 相应角色的菜单列表，并标注首页打勾项
     */
    public Map<String,Object> queryHomePageInfo(RoleHomePageReqDto reqDto){
        Map<String,Object> result=new HashMap<String,Object>();
        //查找所有一级菜单
        List<NavigationListResDto> navList = new ArrayList<>();
        if(currentUserService.CheckIsSysAdmin()){//超级管理员
            navList = rolesMapper.queryAdminParentNavigationList(reqDto.getAppId());
        } else {//普通用户
            navList =  rolesMapper.queryParentNavigationList(currentUserService.getUserId(),reqDto.getRoleId(), reqDto.getAppId());
        }
        if(CollectionUtils.isNotEmpty(navList)){
            //查找所有非一级菜单
            List<NavigationListResDto> allChildList = new ArrayList<>();
            if(currentUserService.CheckIsSysAdmin()){
                allChildList = rolesMapper.queryAdminAllChildNavigationList(reqDto.getAppId());
            } else {
                allChildList = rolesMapper.queryAllChildNavigationList(currentUserService.getUserId(),reqDto.getRoleId(),reqDto.getAppId());
            }
            if(CollectionUtils.isNotEmpty(allChildList)){
                for(NavigationListResDto parent:navList) {
                    queryChildListByParentId(parent,parent.getId(),allChildList);
                }
            }
        }
        YxHomepageConfig yxHomepageConfig = homepageConfigMapper.queryHomePageByRoleId(reqDto.getRoleId(),reqDto.getAppId());
        boolean privilege=true;
        if(!checkPrivilege(reqDto.getRoleId())){
            //登录用户没有该角色的主页操作权限
            privilege=false;
        }
        result.put("navList",navList);
        result.put("check",yxHomepageConfig);
        result.put("privilege",privilege);
        return result;
    }

    //根据父id查找当前子菜单
    private void queryChildListByParentId(NavigationListResDto parent,Integer parentId,List<NavigationListResDto> allChildList){
        List<NavigationListResDto> childList = new ArrayList<>();
        for(NavigationListResDto child : allChildList){
            if(parentId.equals(child.getParentId())){
                queryChildListByParentId(child,child.getId(),allChildList);
                childList.add(child);
            }
        }
        parent.setChildList(childList);
    }

    /**
     * 给角色分配权限
     * @param reqDto 角色分配权限请求实体
     * @return QueryResponse。发生异常时，直接抛出到控制层，控制层catch后处理。
     */
    @Transactional
    public QueryResponse addRoleNavigationRelation(RoleRelateNavigationReqDto reqDto){
        if(!checkPrivilege(reqDto.getRoleId())){
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        //菜单集合
        List<Integer> navList = new ArrayList<>();
        //功能集合
        List<Map<String,Integer>> navFuncMapList = new ArrayList<>();
        //删除角色菜单关联
        YxRolesNavigations rolesNavigations = new YxRolesNavigations();
        rolesNavigations.setRoleId(reqDto.getRoleId());
        rolesNavigationsMapper.deleteRoleNavigations(rolesNavigations);
        //删除角色菜单功能关联
        YxRoleNavigationFunction roleNavigationFunction = new YxRoleNavigationFunction();
        roleNavigationFunction.setRoleId(reqDto.getRoleId());
        roleNavigationFunctionMapper.deleteRoleNavFuncRelation(roleNavigationFunction);

        for(String str:reqDto.getNavAndFuncList()){
            if(str.contains("-")){
                Map<String,Integer> navFuncMap = new HashMap<>();
                String[] strArr = str.split("-");
                navFuncMap.put("functionId",Integer.valueOf(strArr[0]));
                navFuncMap.put("navigationId",Integer.valueOf(strArr[1]));
                navFuncMapList.add(navFuncMap);
            } else {
                navList.add(Integer.valueOf(str));
            }
        }
        Map<String,Object> params = new HashMap<>();
        params.put("loginId",currentUserService.getUserId());//当前登录用户ID
        params.put("roleId",reqDto.getRoleId());
        if(navList.size() > 0){
            //新增角色菜单关联
            params.put("navList",navList);
            rolesNavigationsMapper.addRoleNavigationRelation(params);
        }
        if(navFuncMapList.size() > 0){
            params.put("navFuncMapList",navFuncMapList);
            //新增角色菜单功能关联
            roleNavigationFunctionMapper.addRoleNavFuncRelation(params);
        }
        return new QueryResponse();
    }

    /**
     * 给角色设置主页面
     * @param reqDto 首页设置实体
     * @return QueryResponse。发生异常时，直接抛出到控制层，控制层catch后处理。
     */
    @Transactional
    public QueryResponse insertYxHomepageConfig(YxHomepageConfigReqDto reqDto) {
        if(!checkPrivilege(reqDto.getRoleId())){
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        YxHomepageConfig homepageConfig=new YxHomepageConfig();
        PropertiesUtil.copyProperties(reqDto,homepageConfig);
        Date date = new Date();
        homepageConfig.setCreateTime(date);
        //record.setUpdateTime(date);
        homepageConfig.setType("2");
        homepageConfig.setUserId(reqDto.getRoleId());
        homepageConfig.setCreateBy(0);
        homepageConfigMapper.delHomepageConfigById(reqDto.getRoleId(),reqDto.getAppId());
        homepageConfigMapper.insert(homepageConfig);
        return new QueryResponse();
    }

    public List<Integer> queryUserListByRoleId(Integer roleId) {
        return userRolesMapper.queryUserIdsByRoleId(roleId);
    }

    /**
     * 根据角色ID和appId，查询菜单以及功能，并标识打勾项
     * @param roleId 角色ID
     * @param appId 应用ID
     * @return Map<String, Object> 菜单以及功能Map，并标识打勾项
     */
    public QueryResponse queryRoleNavAndFuncList(Integer roleId, Integer appId){
        //入参校验
        if(null==roleId||null==appId){
           return QueryResponse.setResData(ResultStatus.ERROR_INVALID_ARGUMENT);
        }
        Map<String,Object> result = new HashMap<>();
        //查询登录用户的一级菜单
        List<NavAndFuncLoginResDto> parentList = new ArrayList<NavAndFuncLoginResDto>();
        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        Integer loginUserId=currentUserService.getUserId();
        BaseParmDto<RolesReqDto> parmDto=new BaseParmDto<>();
        Set<Integer> roleIdSet=this.queryRoleIdSet(parmDto);
        roleIdSet.add(roleId);
        if(isSysAdmin) {//超级管理员
            log.info("用户是超级管理员,isSysAdmin:"+isSysAdmin);
            parentList = rolesMapper.queryAdminLoginParentNavList(appId);
        } else {
            log.info("用户是普通用户,isSysAdmin:"+isSysAdmin);
            //普通用户
            parentList =  rolesMapper.queryLoginParentNavList(loginUserId,roleIdSet, appId);
        }
        if(CollectionUtils.isNotEmpty(parentList)){
            //查询登录用户非一级菜单以及功能
            List<NavAndFuncLoginResDto> allChildList = new ArrayList<>();
            if(isSysAdmin){//超级管理员
                allChildList = rolesMapper.queryAdminLoginAllChildNavList(appId);
            } else {
                allChildList = rolesMapper.queryLoginAllChildNavList(loginUserId,roleIdSet,appId);
            }
            if(CollectionUtils.isNotEmpty(allChildList)){
                for(NavAndFuncLoginResDto parent:parentList) {
                    queryChildListByParentId(parent,parent.getId(),allChildList);
                }
            }
        }

        //查询当前用户和角色的菜单以及功能
       // Set<String> checkList = rolesMapper.queryUserRoleCheckNavList(currentUserService.getUserId(),roleId,appId);
        //查询当前角色的菜单以及功能
        Set<String> checkList = rolesMapper.queryRoleCheckNavList(roleId,appId);
        //该菜单是否展开
        Set<String> openList = new HashSet<>();
        if(CollectionUtils.isNotEmpty(parentList) && CollectionUtils.isNotEmpty(checkList)) {
            for(NavAndFuncLoginResDto parentItem:parentList){
                checkUpOpen(openList, parentItem, checkList);
            }
        }
        result.put("navAndFuncList",parentList);
        result.put("checkList",checkList);
        result.put("openList",openList);
        boolean privilege=true;
        if(!checkPrivilege(roleId)){
            //登录用户没有该角色的操作权限
            privilege=false;
        }
        result.put("privilege",privilege);
        return QueryResponse.setResData(result, ResultStatus.SUCCESS);
     }

    //根据父id查找当前子菜单
    private void queryChildListByParentId(NavAndFuncLoginResDto parent,String pid,List<NavAndFuncLoginResDto> allChildList){
        List<NavAndFuncLoginResDto> childList = new ArrayList<>();
        if(!pid.contains("-")){
            for(NavAndFuncLoginResDto child : allChildList){
                if(pid.equals(child.getPid()+"")){
                    queryChildListByParentId(child,child.getId(),allChildList);
                    childList.add(child);
                }
            }
        }
        parent.setChildList(childList);
    }

    //检查是否需要展开
    private void checkUpOpen(Set<String> openList,NavAndFuncLoginResDto parent,Set<String> checkList){
        if(!parent.getId().contains("-")){//非功能
            if(CollectionUtils.isNotEmpty(parent.getChildList())){//当子集合不为空
                for(NavAndFuncLoginResDto child : parent.getChildList()){
                    if(checkList.contains(child.getId())){
                        openList.add(child.getId());
                    }
                    checkUpOpen(openList,child,checkList);
                }
            }
        }
    }
    /**
     * 查询该角色关联的用户列表
     * @param roleUserListReqDto
     * @return
     */
    @Transactional
    public QueryResponse  queryUserList(RoleUserListReqDto roleUserListReqDto){
        long startTime = System.currentTimeMillis();    //获取开始时间
        Integer currentLoginId=currentUserService.getUserId();

        RoleUserListReqPojo roleUserListReqPojo=new RoleUserListReqPojo();
        PropertiesUtil.copyProperties(roleUserListReqDto,roleUserListReqPojo);
        //设置登录用户ID
        roleUserListReqPojo.setLoginUserId(currentLoginId);

        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        log.info("当前登录人是否是超级管理员："+isSysAdmin+"，人员currentLoginId是"+currentLoginId);
        long endTime = System.currentTimeMillis();    //获取结束时间
        log.info("-----11----程序运行时间：" + (endTime - startTime) + "ms");    //输出程序运行时间


        if(isSysAdmin){
            long startTime2 = System.currentTimeMillis();    //获取开始时间
            List<RoleUserListResDto> roleUserListResDtos=rolesMapper.queryUserListForAdmin(roleUserListReqPojo);
            long endTime2 = System.currentTimeMillis();    //获取结束时间
            log.info("-----22----程序运行时间：" + (endTime2 - startTime2) + "ms");    //输出程序运行时间
            return QueryResponse.setResData(roleUserListResDtos, ResultStatus.SUCCESS);
        }


        long startTime3 = System.currentTimeMillis();    //获取开始时间
        // 校验登录用户是不是部门领导
        if(departmentLeaderMapper.countByUserId(currentLoginId)>0){
            //如果是部门，可查询子级部门以及其用户
            Set<Integer> deptIdList=departmentRelationMapper.selectSubDeptIdList(currentLoginId);
            roleUserListReqPojo.setDeptIdList(deptIdList);
            //return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        List<RoleUserListResDto> roleUserListResDtos=rolesMapper.queryUserList(roleUserListReqPojo);
        long endTime3 = System.currentTimeMillis();    //获取结束时间
        log.info("-----33----程序运行时间：" + (endTime3 - startTime3) + "ms");    //输出程序运行时间
        return QueryResponse.setResData(roleUserListResDtos, ResultStatus.SUCCESS);
    }
    public QueryResponse  delUserRoleById(RoleUserDelReqDto roleUserDelReqDto){
        if(!checkPrivilege(roleUserDelReqDto.getRoleId())){
            //登录用户无权限删除
            return new QueryResponse(ResultStatus.ERROR_NO_PRIVILEGE);
        }
        int delNum=userRolesMapper.delUserRoleById(roleUserDelReqDto.getRoleId(),roleUserDelReqDto.getUserId());
        if(delNum>0){
            return new QueryResponse();
        }else{
            return new QueryResponse(ResultStatus.ERROR_DELETE_FAILED);
        }
    }

    /**
     * 给角色分配人员
     * @param roleUserReqDto
     * @return
     */
    @Transactional
    public QueryResponse insertRoleUsers(RoleUserReqDto roleUserReqDto) {
        long startTime = System.currentTimeMillis();    //获取开始时间
        Integer oneInteger=new Integer(1);
        Integer roleId=roleUserReqDto.getRoleId();
        List<String> idList=roleUserReqDto.getIdList();
        List<YxUserRoles> userRoleList=new ArrayList<YxUserRoles>();
        Set<Integer> deptIdSet=new HashSet<>();
        Set<Integer> userIdSet=new HashSet<>();
        Integer loginId=currentUserService.getUserId();
        for(String idItem:idList){
            if(StringUtils.isEmpty(idItem)){
                continue;
            }
            if(idItem.startsWith("dept_")){
                String idStr=idItem.substring(5,idItem.length());
                deptIdSet.add(Integer.valueOf(idStr));
                continue;
            }
            userIdSet.add(Integer.parseInt(idItem));
        }
        long endTime = System.currentTimeMillis();    //获取结束时间
        log.info("-------11---------程序运行时间：" + (endTime - startTime) + "ms");    //输出程序运行时间

        if(CollectionUtils.isNotEmpty(deptIdSet)){
            if(deptIdSet.contains(oneInteger)){
                long startTime4 = System.currentTimeMillis();    //获取开始时间
                //1：乂学教育，部门ID传1到本接口，表示操作员将该角色分给全部用户
                long startTime5 = System.currentTimeMillis();    //获取开始时间
                List<Integer> allUserId=userRolesMapper.queryAllUserId();
                long endTime5 = System.currentTimeMillis();    //获取结束时间
                log.info("-------55--查询所有用户ID------程序运行时间：" + (endTime5 - startTime5) + "ms");    //输出程序运行时间
                long startTime6 = System.currentTimeMillis();    //获取开始时间
                for (Integer userId:allUserId) {
                    YxUserRoles userRole = new YxUserRoles(userId,roleId,loginId);
                    userRoleList.add(userRole);
                }
                long endTime6 = System.currentTimeMillis();    //获取结束时间
                log.info("-------66--将所有用户ID封装成YxUserRoles对象集合------程序运行时间：" + (endTime6 - startTime6) + "ms");    //输出程序运行时间
                log.info("-----------------用户数userRoleList.size()="+userRoleList.size());

                if(userRoleList.size()>0){
                    userRolesMapper.deleteByRoleId(roleId);
                    long startTime7 = System.currentTimeMillis();    //获取开始时间
                    userRolesMapper.insertBatch(userRoleList);
                    long endTime7 = System.currentTimeMillis();    //获取结束时间
                    log.info("-------77----批量插入----程序运行时间：" + (endTime7 - startTime7) + "ms");    //输出程序运行时间
                }
                long endTime4 = System.currentTimeMillis();    //获取结束时间
                log.info("-------44---------程序运行时间：" + (endTime4 - startTime4) + "ms");    //输出程序运行时间
                log.info("程序运行时间：" + (endTime4 - startTime) + "ms");    //输出程序运行时间
                return new QueryResponse();
            }
        }

        List<String> delIdList=roleUserReqDto.getDelIdList();
        Set<Integer> delDeptIdSet=new HashSet<>();
        Set<Integer> delUserIdSet=new HashSet<>();
        if(!CollectionUtils.isEmpty(delIdList)) {
            for (String idItem : delIdList) {
                if (StringUtils.isEmpty(idItem)) {
                    continue;
                }
                if (idItem.startsWith("dept_")) {
                    String idStr = idItem.substring(5, idItem.length());
                    delDeptIdSet.add(Integer.valueOf(idStr));
                    continue;
                }
                delUserIdSet.add(Integer.parseInt(idItem));
            }
        }
        Set<Integer> userIdDbDelSet=new HashSet<>();
        if(CollectionUtils.isNotEmpty(delDeptIdSet)){
            if(delDeptIdSet.contains(oneInteger)){
                List<Integer> allUserId=userRolesMapper.queryAllUserId();
                userIdDbDelSet.addAll(allUserId);
            }else{
                userIdDbDelSet=departmentRelationMapper.selectUserIdSetByDeptIdSet(delDeptIdSet);
            }
        }

        if(CollectionUtils.isNotEmpty(delUserIdSet)){
            delUserIdSet.addAll(userIdDbDelSet);
        }else {
            delUserIdSet=userIdDbDelSet;
        }

        //根据角色ID，读取该角色已有全部的用户ID集合
        Set<Integer> allUserId=userRolesMapper.queryAllUserIdByRoleId(roleId);
        Set<Integer> userIdDbSet=new HashSet<>();
        if(CollectionUtils.isNotEmpty(deptIdSet)){
            //根据传入的部门ID集合，读取用户ID集合
            userIdDbSet=departmentRelationMapper.selectUserIdSetByDeptIdSet(deptIdSet);
        }

        //将数据库中的用户ID集合、前端传入的用户ID集合、以及将前端传来的部门ID转换为用户ID集合，
        //作并集处理，并去重
        Set<Integer> userIdUnionSet=new HashSet<>();
        userIdUnionSet.addAll(allUserId);
        if(CollectionUtils.isNotEmpty(userIdUnionSet)){
            userIdUnionSet.removeAll(delUserIdSet);
        }
        userIdUnionSet.addAll(userIdDbSet);
        userIdUnionSet.addAll(userIdSet);

        for (Integer userId:userIdUnionSet) {
            YxUserRoles userRole = new YxUserRoles(userId,roleId,loginId);
            userRoleList.add(userRole);
        }
        userRolesMapper.deleteByRoleId(roleId);
        if(userRoleList.size()>0){
            userRolesMapper.insertBatch(userRoleList);
        }

        /*if(CollectionUtils.isNotEmpty(delUserIdSet)){
            userRolesMapper.delByUserIdSet(delUserIdSet);
        }*/
        long endTime3 = System.currentTimeMillis();    //获取结束时间
        //log.info("-------33---------程序运行时间：" + (endTime3 - startTime3) + "ms");    //输出程序运行时间
        log.info("程序运行时间：" + (endTime3 - startTime) + "ms");    //输出程序运行时间

        return new QueryResponse();
    }

    /**
     * 验证登录用户是否拥有该角色的操作权限
     * @param roleId 角色ID
     * @return true:有操作权限 false:无操作权限
     */
    boolean checkPrivilege(Integer roleId){
        boolean result=true;
        if(null==roleId){
            log.info("rolesService.checkPrivilege():roleId is null");
            return false;
        }
        //isSuperAdmin 是否是超级管理员 true:是 false:否
        boolean isSuperAdmin=currentUserService.CheckIsSysAdmin();
        if(isSuperAdmin){
            //当操作用户是超级管理员,拥有所有角色的管理权限
            return true;
        }
        YxRoles role=rolesMapper.selectByRoleId(roleId);
        if(null==role){
            log.info("rolesService.checkPrivilege():role is null");
            return false;
        }
        //isBuiltin 0:非系统角色 1：系统角色(只有超级管理员可以修改）
        Integer isBuiltin=role.getIsBuiltin();
        //当操作用户不是超级管理员，并且角色类型是系统角色，则认为无权限操作
        if((!isSuperAdmin)&&1==isBuiltin){
            result=false;
        }
        return result;
    }

    /**
     * 查询当前登录人的角色ID集合
     * @param parmDto
     * @return
     */
    public  Set<Integer> queryRoleCampusIdsSet(BaseParmDto<RolesReqDto> parmDto) {
        Integer campusCode= DepartmentLevelTypeEnum.Campus.getCode();
        RolesReqDto reqDto=parmDto.getParam();
        RolesReqPojo rolesReqPojo=new RolesReqPojo();
        PropertiesUtil.copyProperties(reqDto,rolesReqPojo);
        //当前登录用户
        Integer userId=currentUserService.getUserId();
        rolesReqPojo.setUserId(userId);
        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        log.info("当前登录人是否是超级管理员："+isSysAdmin+"，人员ID是"+userId);
        rolesReqPojo.setSysAdmin(isSysAdmin);
       /*  Set<Integer> leaderIdList =new HashSet<Integer>();
        //判断登录用户是部门领导，还是普通用户
       if(departmentLeaderMapper.countByUserId(userId)>0){
            log.info("当前登录人是部门领导，人员ID是"+userId);
            //大于0，说明是部门领导
            Set<Integer> deptIdList=departmentRelationMapper.selectChildDeptIdList(userId);
            if(CollectionUtils.isNotEmpty(deptIdList)){
                leaderIdList =departmentLeaderMapper.queryUserIdListByDeptIds(deptIdList);
            }
            rolesReqPojo.setUserIdList(leaderIdList);
        }*/
        Page<Object> page = PageHelper.startPage(parmDto.getPageIndex(), parmDto.getPageSize());
        List<RoleListResDto> resDtosList = rolesMapper.queryRoleListByPage(rolesReqPojo);
        //校区级别，campusLevelType==6001001，展示校区名字。campusLevelType!=6001001，将campusName重置为空
        boolean flag=false;
        for (RoleListResDto roleListResDto:resDtosList){
            Integer campusLevelType=roleListResDto.getCampusLevelType();
            if((!campusCode.equals(campusLevelType))||(null==campusLevelType)){
                //非校区的角色，campusName显示"无"
                roleListResDto.setCampusName("无");
                flag=true;
                break;
            }
        }
        Set<Integer> roleCampusIdSet=new HashSet<Integer>();
        if(flag){
            roleCampusIdSet.add(0);
        }
        for(RoleListResDto roleListResDto:resDtosList){
            roleCampusIdSet.add( roleListResDto.getCampusId());
        }
        return roleCampusIdSet;
    }

    /**
     * 查询当前登录人所有的角色ID集合（SET）
     * @param parmDto
     * @return
     */
    public  Set<Integer> queryRoleIdSet(BaseParmDto<RolesReqDto> parmDto) {
        Integer campusCode= DepartmentLevelTypeEnum.Campus.getCode();
        RolesReqDto reqDto=parmDto.getParam();
        RolesReqPojo rolesReqPojo=new RolesReqPojo();
        PropertiesUtil.copyProperties(reqDto,rolesReqPojo);
        //当前登录用户ID
        Integer loginUserId=currentUserService.getUserId();
        rolesReqPojo.setUserId(loginUserId);
        boolean isSysAdmin=currentUserService.CheckIsSysAdmin();
        log.info("当前登录人是否是超级管理员："+isSysAdmin+"，人员ID是"+loginUserId);
        rolesReqPojo.setSysAdmin(isSysAdmin);
        /*Set<Integer> leaderIdList =new HashSet<Integer>();
        //判断登录用户是部门领导，还是普通用户
        if(departmentLeaderMapper.countByUserId(loginUserId)>0){
            log.info("当前登录人是部门领导，人员ID是"+loginUserId);
           //大于0，说明是部门领导
            Set<Integer> deptIdList=departmentRelationMapper.selectChildDeptIdList(loginUserId);
            if(CollectionUtils.isNotEmpty(deptIdList)){
                leaderIdList =departmentLeaderMapper.queryUserIdListByDeptIds(deptIdList);
            }
            rolesReqPojo.setUserIdList(leaderIdList);
       }*/
        List<RoleListResDto> resDtosList = rolesMapper.queryRoleListByPage(rolesReqPojo);
        Set<Integer> resultSet=new TreeSet<>();
        //校区级别，campusLevelType==6001001，展示校区名字。campusLevelType!=6001001，将campusName重置为"无"
        Integer oneObj=new Integer(1);
        for (RoleListResDto roleListResDto:resDtosList){
            resultSet.add(roleListResDto.getRoleId());
        }
        return resultSet;
    }

    //该方法暂时没有使用
    public List<Integer> queryUserIdsByDeptId(Integer deptId){
        if(yxDepartmentsMapper.selectById(deptId) == null){
            throw new BusinessException(DepartmentError.ERROR_DEPARTMENT_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }
        //包含子部门的成员
        Set<Integer> departmentAll =  departmentRelationMapper.selectSubIdListByDeptId(deptId);
        UserIdsForRolePojo userIdsForRolePojo=new UserIdsForRolePojo();
        userIdsForRolePojo.setDepartmentId(deptId);
        if(CollectionUtils.isNotEmpty(departmentAll)) {
            userIdsForRolePojo.setDepartmentIds(departmentAll);
            userIdsForRolePojo.setExistSubDept(true);
        }
        return yxDepartmentUserMapper.queryUserIdsByDeptId(userIdsForRolePojo);
    }

    //该方法暂时没有使用
    //检查是否需要展开
    private void checkUpOpen(Set<String> openList,NavAndFuncRoleResDto parent,Set<String> checkList){
        if(!parent.getId().contains("-")){//非功能
            if(CollectionUtils.isNotEmpty(parent.getChildList())){//当子集合不为空
                for(NavAndFuncRoleResDto child : parent.getChildList()){
                    if(checkList.contains(child.getId())){
                        openList.add(child.getId());
                    }
                    checkUpOpen(openList,child,checkList);
                }
            }
        }
    }

    //该方法暂时没有使用
    //根据父id查找当前子菜单
    private void queryChildListByParentId(NavAndFuncRoleResDto parent,String pid,List<NavAndFuncRoleResDto> allChildList){
        List<NavAndFuncRoleResDto> childList = new ArrayList<>();
        if(!pid.contains("-")){
            for(NavAndFuncRoleResDto child : allChildList){
                if(pid.equals(child.getPid()+"")){
                    queryChildListByParentId(child,child.getId(),allChildList);
                    childList.add(child);
                }
            }
        }
        parent.setChildList(childList);
    }

}
